package onlinebanking.network;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class SimpleNetworkSwitch implements NetworkSwitch {
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;

	/**
	 * Creates an instance of a <code>NetworkSwitch</code>.
	 * 
	 * @param socket
	 *            The <code>Socket</code> to be wrapped.
	 */
	public SimpleNetworkSwitch(Socket socket) {
		this.socket = socket;
		try {
			this.in = new BufferedReader(new InputStreamReader(
					this.socket.getInputStream()));
			this.out = new PrintWriter(new OutputStreamWriter(
					this.socket.getOutputStream()));
		} catch (IOException e) {
			System.out.println("Error occured:");
			e.printStackTrace();
		}
	}

	/**
	 * Send a message to the network.
	 * 
	 * @param message
	 *            The message to be sent.
	 * @return <code>true</code> if message sent successfully,
	 *         <code>false</code> otherwise.
	 */
	@Override
	public boolean send(String message) {
		try {
			this.out.println(message);
			this.out.flush();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * Receives a message from the network.
	 * 
	 * @return the Message object received.
	 * @throws IOException
	 */
	public String receive() throws IOException {
		return this.in.readLine();
	}

}
